import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from app_models.models import Books

class BooksView(View):
    def get(self, request):
        books = Books.objects.filter(is_delete=False)
        book_list = []
        for book in books:
            book_data = {
                "id": book.id,
                "btitle": book.btitle,
                "bpub_date": book.bpub_date,
                "bread": book.bread,
                "bcomment": book.bcomment
            }
            book_list.append(book_data)
        data = {
            "code": 0,
            "msg": "success",
            "books": book_list
        }
        return JsonResponse(data)

    def post(self, request):
        body_json = request.body.decode()
        body_dict = json.loads(body_json)
        btitle = body_dict.get('btitle')
        bpub_date = body_dict.get('bpub_date')
        bread = body_dict.get('bread')
        bcomment = body_dict.get('bcomment')
        book = Books(btitle=btitle, bpub_date=bpub_date, bread=bread, bcomment=bcomment)
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})
class Update_Book(View):
    def post(self, request):
        body_json = request.body.decode()
        body_dict = json.loads(body_json)
        id = body_dict.get('id')
        btitle = body_dict.get('btitle')
        bpub_date = body_dict.get('bpub_date')
        bread = body_dict.get('bread')
        bcomment = body_dict.get('bcomment')
        book = Books.objects.get(id=id)
        book.btitle = btitle
        book.bpub_date = bpub_date
        book.bread = bread
        book.bcomment = bcomment
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})
class DelView(View):
    def post(self, request):
        body_json = request.body.decode()
        body_dict = json.loads(body_json)
        id = body_dict.get('id')
        book = Books.objects.get(id=id)
        book.is_delete = True
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})